package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.Album;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.pojo.Publish;
import com.tanhua.dubbo.pojo.TimeLine;
import com.tanhua.dubbo.service.IdService;
import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询好友动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageRequest);

        //查询到好友的发布的动态id
        List<TimeLine> timeLineList =
                this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        if (CollUtil.isEmpty(timeLineList)) {
            return pageInfo;
        }

        //获取到发布的id列表
        List<Object> publishIdList = CollUtil.getFieldValues(timeLineList, "publishId");
        Query publishQuery = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));

        //发布列表
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    /**
     * 发布动态
     *
     * @param publish
     * @return 发布成功返回动态id
     */
    @Override
    public String savePublish(Publish publish) {
        //校验对象中的数据是否正确
        if (!ObjectUtil.isAllNotEmpty(publish.getUserId(), publish.getText())) {
            return null;
        }

        publish.setId(ObjectId.get()); //主键id
        publish.setCreated(System.currentTimeMillis());
        publish.setPid(this.idService.createId(IdType.PUBLISH)); //自增长id
        publish.setSeeType(1); //默认可见类型

        //写入发布表
        this.mongoTemplate.save(publish);

        //写入到相册表（自己的数据）
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //写入到好友的时间线表中（异步写入）
        this.timeLineService.saveTimeLine(publish);

        //返回动态id
        return publish.getId().toString();
    }

    /**
     * 查询推荐动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page,
                                                       Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从redis中查询推荐的数据
        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String redisValue = this.redisTemplate.opsForValue().get(redisKey);

        if (StrUtil.isEmpty(redisValue)) {
            return pageInfo;
        }

        //pid列表 目前有20个，每一页查5个
        List<String> pidStrList = StrUtil.split(redisValue, ',');
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0];
        int endIndex = Math.min(startEnd[1], pidStrList.size());

        List<Long> pidList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidList.add(Convert.toLong(pidStrList.get(i)));
        }

        if (CollUtil.isEmpty(pidList)) {
            return pageInfo;
        }

        Query query = Query.query(Criteria.where("pid").in(pidList));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);

        List<Publish> result = new ArrayList<>();
        //按照推荐顺序排序
        for (Long pid : pidList) {
            for (Publish publish : publishList) {
                if (ObjectUtil.equal(publish.getPid(), pid)) {
                    result.add(publish);
                    break;
                }
            }
        }

        pageInfo.setRecords(result);
        return pageInfo;
    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断用户是否已经点赞
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(publishId));
        comment.setCreated(System.currentTimeMillis());
        comment.setIsParent(false);

        //查询发动的动态数据
        Publish publish = this.queryPublishById(publishId);
        if (null == publish) {
            //传入非法的id
            return false;
        }
        comment.setPublishUserId(publish.getUserId());

        //存储到MongoDB
        this.mongoTemplate.save(comment);

        //把点赞数、用户是否点赞存储到redis中
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        hashKey = this.getCommentUserLikeRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户是否已经取消点赞
        if (!this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除MongoDB中点赞数据
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(CommentType.LIKE.getType()));
        DeleteResult deleteResult = this.mongoTemplate.remove(query, Comment.class);
        if (deleteResult.getDeletedCount() == 0) {
            return false;
        }

        //在redis中更新点赞数、用户是否点赞
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        hashKey = this.getCommentUserLikeRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey);

        return true;
    }

    /**
     * 查询点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询相册
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        if (CollUtil.isEmpty(albumList)) {
            return pageInfo;
        }

        //查询动态
        Query publishQuery = Query.query(Criteria.where("id")
                .in(CollUtil.getFieldValues(albumList, "publishId")))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }
}
